﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.Common.Utility
{
    /// <summary>
    /// Excel工具类
    /// </summary>
    public static class ExcelUtil
    {
        /// <summary>
        /// 导出流
        /// </summary>
        /// <param name="list">数据集</param>
        /// <returns>流</returns>
        public static Stream ToStream(this List<Dictionary<String, Object>> list)
        {
            //创建工作薄
            var workbook = new HSSFWorkbook();

            //创建表
            var worksheet = workbook.CreateSheet();

            var title = list.FirstOrDefault();

            var row = worksheet.CreateRow(0);

            var index = 0;

            var cell = row.CreateCell(index);

            cell.SetCellValue("序号");

            index++;

            foreach (var item in title)
            {
                cell = row.CreateCell(index);
                cell.SetCellValue(item.Key);
                cell.CellStyle.WrapText = true;

                index++;
            }

            for (var i = 1; i <= list.Count; i++)
            {
                row = worksheet.CreateRow(i);

                index = 0;

                cell = row.CreateCell(index);
                cell.SetCellValue(i);
                cell.CellStyle.WrapText = true;
                cell.CellStyle.VerticalAlignment = VerticalAlignment.Center;
                cell.CellStyle.Alignment = HorizontalAlignment.Center;

                index++;

                foreach (var item in list[i - 1])
                {
                    cell = row.CreateCell(index);
                    cell.SetCellValue(item.Value.ToString());
                    cell.CellStyle.WrapText = true;

                    index++;
                }
            }

            MemoryStream stream = new MemoryStream();

            //将工作薄写入文件流
            workbook.Write(stream);
            workbook.Close();

            return stream;
        }
    }
}
